import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api/index.js'
import md5 from 'js-md5'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const uid = ref(localStorage.getItem('uid') || '')
  const username = ref(localStorage.getItem('username') || '')

  const isAuthenticated = computed(() => !!token.value)

  const login = async (loginUsername, loginPassword) => {
    try {
      // 使用js-md5库对密码进行MD5加密
      const md5Password = md5(loginPassword);
      
      const response = await api.post('/auth/login', { username: loginUsername, password: md5Password })
      
      // 响应拦截器已经处理了统一格式，response就是data数据
      const { token: userToken, uid: userId, username: userName } = response
      
      token.value = userToken
      uid.value = userId.toString()
      username.value = userName

      localStorage.setItem('token', userToken)
      localStorage.setItem('uid', userId.toString())
      localStorage.setItem('username', userName)

      return { success: true, data: response }
    } catch (error) {
      let errorMessage = '登录失败'
      
      if (error.response?.data?.detail) {
        errorMessage = error.response.data.detail
      } else if (error.response?.status === 401) {
        errorMessage = '用户名或密码错误'
      } else if (error.message) {
        errorMessage = error.message
      }

      return { 
        success: false, 
        error: errorMessage 
      }
    }
  }

  const logout = () => {
    token.value = ''
    uid.value = ''
    username.value = ''

    localStorage.removeItem('token')
    localStorage.removeItem('uid')
    localStorage.removeItem('username')
  }

  const checkAuth = () => {
    return !!token.value
  }

  return {
    token,
    uid,
    username,
    isAuthenticated,
    login,
    logout,
    checkAuth
  }
})